package org.zebra.web.annotation.validation;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.lang.Validator;
import cn.hutool.core.text.CharSequenceUtil;

import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;
import java.util.Date;

/**
 * 生日格式校验器
 *
 * @author	zhanghongbin
 */
public class BirthdayValidator implements ConstraintValidator<Birthday, Object> {

    private boolean notNull;

    @Override
    public void initialize(Birthday constraintAnnotation) {
        this.notNull = constraintAnnotation.notNull();
    }

    @Override
    public boolean isValid(Object value, ConstraintValidatorContext context) {
        String validValue = null;
        if (value instanceof String) {
            validValue = (String) value;
        } else if (value instanceof Date) {
            validValue = DateUtil.formatDate((Date) value);
        }
        if (CharSequenceUtil.isNotBlank(validValue)) {
            return Validator.isBirthday(validValue);
        }
        if (notNull) {
            return false;
        }
        return true;
    }
}
